<template>
  <div
    class="app-container flex flex-sub"
    style="background: none; height: 100%; padding: 1rem"
  >
    <div class="flex" style="width: 380px; height: 100%">
      <el-card shadow="never" class="box-card flex-sub" style="overflow: auto">
        <div
          style="border: 1px solid #c8c8c8; padding: 0.7rem; margin-top: 1rem"
        >
          <div
            class="flex"
            style="margin-bottom: 1rem; justify-content: space-between"
          >
            <el-button size="small" @click="toExpandAll('是')">
              <i class="el-icon-plus" style="color: #606266" />
              <span style="color: #606266">全部展开</span>
            </el-button>

            <el-button size="small" @click="toExpandAll('否')">
              <i class="el-icon-minus" style="color: #606266" />
              <span style="color: #606266">全部收起</span>
            </el-button>

            <el-button size="small" @click="toRefreshGridTree">
              <i class="el-icon-refresh" style="color: #606266" />
              <span style="color: #606266">刷新</span>
            </el-button>
          </div>
          <el-input
            v-model="gridName"
            style="margin-bottom: 1rem"
            placeholder="请输入网格名称"
            prefix-icon="el-icon-search"
            class="filter-item search-item"
            @keyup.native="toSearchGridTree"
          />

            <div
            style="margin-right: 0px; overflow: auto"
            :style="{ height: gridTreeHeight }"
            class="box-card"
          >
          <el-tree
            ref="refGridTree"
            :data="gridTree"
            node-key="id"
            :filter-node-method="filterNode"
            :highlight-current="highlightCurrent"
            :expand-on-click-node="expandOnClickNode"
            :default-expand-all="expandAll"
            @node-click="nodeCick"
          />
            </div>
        </div>
      </el-card>
    </div>

    <div
      class="flex flex-sub"
      style="margin-left: 1rem; width: calc(100% - 390px)"
    >
      <el-card shadow="never" class="box-card flex-sub" style="overflow: auto">
        <div class="div-query">
          <div class="collapse">
            <div class="collapse-header" @click="panelActive = !panelActive">
              <i
                class="collapse-header-icon"
                :class="[
                  panelActive ? 'el-icon-caret-bottom' : 'el-icon-caret-top',
                ]"
              />
              {{ panelActive ? '隐藏' : '展开' }}查询条件
            </div>
            <div class="collapse-content">
              <el-collapse-transition>
                <div v-show="panelActive">
                  <el-form size="small" label-position="right">
                    <el-row>
                      <el-col :span="8">
                        <el-form-item label="设备编码" label-width="80px">
                          <el-input
                            v-model="searchModel.deviceCode"
                            placeholder="设备编码"
                            clearable
                            class="filter-item search-item"
                          />
                        </el-form-item>
                      </el-col>

                      <el-col :span="8">
                        <el-form-item label="设备名称" label-width="80px">
                          <el-input
                            v-model="searchModel.deviceName"
                            placeholder="设备名称"
                            clearable
                            class="filter-item search-item"
                          />
                        </el-form-item>
                      </el-col>
                      <el-col :span="8">
                        <el-form-item style="margin-left: 10px">
                          <el-button
                            type="primary"
                            icon="el-icon-search"
                            @click="toSearch"
                            style="margin-right: 10px"
                            >搜素</el-button
                          >
                          <el-button
                            type="info"
                            icon="el-icon-delete"
                            @click="toReset"
                            >重置</el-button
                          >
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </el-form>
                </div>
              </el-collapse-transition>
            </div>
          </div>
        </div>

        <el-button
          v-show="gridrow.guid"
          type="primary"
          icon="el-icon-plus"
          @click="addDevice"
          style="margin-bottom: 1rem"
          >添加设备</el-button
        >

        <el-table
          ref="elTable"
          border
          fit
          size="medium "
          v-loading="loading"
          :data="activeList"
          :row-key="(row) => row.id"
          style="width: 100%"
        >
          <af-table-column align="center" label="设备编码" prop="deviceCode" />
          <af-table-column align="center" label="设备名称" prop="deviceName" />
          <af-table-column
            align="center"
            label="设备位置"
            prop="deviceLocation"
          />

          <af-table-column
            align="center"
            label="x,y,z轴点位"
            prop="localPosition"
          >
          </af-table-column>

          <el-table-column
            align="center"
            label="操作区"
            fixed="right"
            width="100"
          >
            <template slot-scope="{ row }">
              <el-tooltip effect="dark" content="编辑" placement="top-start">
                <i
                  class="iconfont icon-bianji2 i-edit"
                  @click="editDevice(row)"
                />
              </el-tooltip>
              <i class="iconfont icon-fengefu i-fengefu" />

              <el-tooltip effect="dark" content="解绑" placement="top-start">
                <i
                  class="iconfont icon-shanchu i-delete"
                  @click="deleteDevice(row)"
                />
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="pagination.pageNum"
          :limit.sync="pagination.pageSize"
          :page-sizes="pageSizeOptions"
          @pagination="getActiveDevice"
        />
      </el-card>
    </div>

    <el-dialog
      top="80px"
      :visible.sync="gridDeviceVisible"
      :title="'设备关联：' + gridrow.fullPathText"
      :before-close="modalClose"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="50%"
      size="small"
    >
      <el-container>
        <el-main>
          <div class="title">
            <span>填写信息</span>
          </div>
          <el-card class="card" shadow="never" style="background: #fafafa">
            <el-form
              :model="ruleForm"
              ref="ruleForm"
              size="small"
              :rules="rules"
              label-width="100px"
              class="demo-ruleForm"
            >
              <el-form-item label="设备名称" prop="deviceName">
                <el-select
                  v-model="ruleForm.deviceName"
                  filterable
                  remote
                  reserve-keyword
                  placeholder="输入关键词"
                  :remote-method="remoteMethod"
                  :loading="loading"
                  @change="returnItem"
                >
                  <el-option
                    v-for="item in deviceList"
                    :key="item.deviceCode"
                    :label="item.deviceName"
                    :value="item.deviceCode"
                  >
                    <span style="float: left">{{ item.deviceName }}</span>
                    <span style="float: right">{{ item.deviceCode }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="设备编码" prop="deviceCode">
                <el-input v-model="ruleForm.deviceCode" disabled></el-input>
              </el-form-item>
              <el-form-item label="模型ID" prop="modelId">
                <el-input
                  v-model="ruleForm.modelId"
                  placeholder="输入模型id"
                ></el-input>
              </el-form-item>
              <el-form-item label="模型坐标" prop="localPosition">
                <el-input
                  v-model="ruleForm.localPosition"
                  placeholder="输入坐标以逗号分隔"
                ></el-input>
              </el-form-item>
              <!-- <el-form-item>
                <el-button
                  v-if="btnType == '添加'"
                  type="primary"
                  @click="submitDevice('ruleForm')"
                  >添加</el-button
                >
                <el-button
                  v-if="btnType == '编辑'"
                  type="primary"
                  @click="submitDevice('ruleForm')"
                  >编辑</el-button
                >
                <el-button @click="resetForm('ruleForm')">重置</el-button>
              </el-form-item> -->
            </el-form>
          </el-card>
        </el-main>
        <el-footer>
          <el-button
            v-if="btnType == '添加'"
            type="primary"
            @click="submitDevice('ruleForm')"
            style="margin-right: 10px"
            >添加</el-button
          >
          <el-button
            v-if="btnType == '编辑'"
            type="primary"
            @click="submitDevice('ruleForm')"
            style="margin-right: 10px"
            >编辑</el-button
          >
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-footer>
      </el-container>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import GridManageApi from '@/api/grid-manage'
import dataTableMixins from '@/mixins/data-table-mixins'
import deviceManageApi from '@/api/device-manage'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
  name: 'GridList',
  components: {
    Pagination,
    Treeselect,
  },
  mixins: [dataTableMixins],
  data() {
    return {
      gridTreeHeight: this.getHeightAndWidth(),
      gridTree: [],
      gridName: '',
      gridDeviceVisible: false,
      expandOnClickNode: false,
      expandAll: false,
      highlightCurrent: true,
      // JsonVisible:false,
      total: 0,
      deviceList: [],
      btnType: '添加',
      ruleForm: {
        gridMount: '',
        gridMountFullPath: '',
        gridMountFullPathText: '',
        deviceName: '',
        deviceCode: '',
        modelId: '',
        localPosition: '',
      },
      // 表单校验
      rules: {
        deviceName: [
          { required: true, message: '请输入设备名称', trigger: 'change' },
        ],
        modelId: [{ required: true, message: '请输入模型ID', trigger: 'blur' }],
        // deviceCode: [{ required: true, message: "请输入活动名称", trigger: "blur" }],
        localPosition: [
          { required: true, message: '请输入模型坐标', trigger: 'blur' },
        ],
      },
      searchModel: {
        deviceCode: '',
        deviceName: '',
      },
      activeList: [],
      gridrow: {},
    }
  },
  watch: {
    gridName(val) {
      this.$refs.refGridTree.filter(val)
    },
  },
  mounted() {
    this.getGridTree()
  },
  methods: {
    addDevice() {
      this.ruleForm = {
        gridMount: '',
        gridMountFullPath: '',
        gridMountFullPathText: '',
        deviceName: '',
        deviceCode: '',
        modelId: '',
        localPosition: '',
      }
      this.gridDeviceVisible = true
      this.btnType = '添加'
    },
    editDevice(row) {
      this.ruleForm.deviceCode = row.deviceCode
      this.ruleForm.deviceName = row.deviceName
      this.ruleForm.modelId = row.modelId
      this.ruleForm.localPosition = row.localPosition
      this.gridDeviceVisible = true
      this.btnType = '编辑'
    },
    deleteDevice(row) {
      let obj = {
        deviceCode: row.deviceCode,
      }
      this.$confirm('此操作会解绑设备, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          deviceManageApi.unbind(obj).then((res) => {
            this.$message({
              type: 'success',
              message: '解绑成功!',
            })
            this.getActiveDevice()
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消解绑',
          })
        })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    // creatJson() {
    //  this.JsonVisible= true
    // },
    // addGridDevice
    submitDevice(formName) {
      // .match(/,|，/g)
      this.$refs[formName].validate((valid) => {
        if (valid) {
          deviceManageApi
            .addGridDevice(JSON.stringify(this.ruleForm))
            .then((res) => {
              this.$message({
                message: this.btnType + '成功',
                type: 'success',
              })
              this.gridDeviceVisible = false
              this.ruleForm.deviceName = ''
              this.ruleForm.deviceCode = ''
              this.ruleForm.modelId = ''
              this.ruleForm.localPosition = ''
              this.getActiveDevice()
              this.toReset()
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    remoteMethod(query) {
      this.getDataList(query)
      if (query !== '') {
        this.loading = true
        setTimeout(() => {
          this.loading = false
          this.deviceList = this.deviceList.filter((item) => {
            return (
              item.deviceName.toLowerCase().indexOf(query.toLowerCase()) > -1
            )
          })
          // console.log( this.deviceList);
        }, 200)
      } else {
        this.options = []
      }
    },
    returnItem(value) {
      let obj = this.deviceList.filter((item) => item.deviceCode == value)[0]
      this.ruleForm.deviceName = obj.deviceName
      this.ruleForm.deviceCode = obj.deviceCode
    },
    getHeightAndWidth() {
      let clientHeight = 0
      if (
        document.body.scrollHeight === window.screen.height &&
        document.body.scrollWidth === window.screen.width
      ) {
        clientHeight = window.screen.height - 5 // 网页可见区域高
      } else {
        clientHeight = document.body.clientHeight - 5 // 网页可见区域高
      }
      return clientHeight - 320 + 'px'
    },

    getGridTree() {
      GridManageApi.getGridTree()
        .then((res) => {
          this.gridTree = res.data.data.rows
        })
        .catch(() => {
          this.gridTree = []
        })
    },
    getDataList(query) {
      this.loading = true
      let ruleForm = {
        deviceName: query,
      }

      deviceManageApi
        .getDeviceList({ ...this.pagination, ...ruleForm, ...this.sort })
        .then((ret) => {
          this.deviceList = ret.data.data.rows
          console.log(this.deviceList)
          this.loading = false
        })
        .catch(() => {
          this.loading = false
          this.deviceList = []
        })
    },
    toSearchGridTree() {
      this.$refs.refGridTree.filter(this.gridName)
    },
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    nodeCick(data) {
      this.gridrow = { ...data }
      console.log(data, 'xxxxxxxxxx')
      this.ruleForm.gridMount = data.guid
      this.ruleForm.gridMountFullPathText = data.fullPathText
      this.ruleForm.gridMountFullPath = data.fullPath
      this.getActiveDevice()
    },

    toSearch() {
      this.pagination.pageNum = 1
      this.getActiveDevice()
    },
    toReset() {
      this.searchModel = {
        deviceCode: '',
        deviceName: '',
      }
      this.getActiveDevice()
    },
    getActiveDevice() {
      let obj = {
        gridMount: this.gridrow.guid,
      }
      GridManageApi.getGridDeviceActive({
        ...this.pagination,
        ...obj,
        ...this.searchModel,
      }).then((res) => {
        console.log(res, 'xxx')
        this.total = res.data.data.total
        this.activeList = res.data.data.rows
      })
    },
    modalClose() {
      this.gridDeviceVisible = false // 直接修改父组件的属性
    },

    toRefreshGridTree() {
      this.gridName = ''
      this.getGridTree()
    },
    toExpandAll(text) {
      if (text === '是') {
        this.expandAll = true
      } else {
        this.expandAll = false
      }
      for (
        var i = 0;
        i < this.$refs.refGridTree.store._getAllNodes().length;
        i++
      ) {
        this.$refs.refGridTree.store._getAllNodes()[i].expanded = this.expandAll
      }

      // console.log('测试')
      // this.$refs.refGridTree.$children.forEach(
      //   (item) => (item.expanded = this.expandAll)
      // )
    },
  },
}
</script>



<style lang="scss" scoped>
@import '../../../../../styles/part-custom';
.right-menu {
  z-index: 1;
  position: absolute;
  width: 150px;
  position: absolute;
  border-radius: 5px;
  list-style: none;
  background: linear-gradient(rgb(246, 247, 249) 0%, rgb(235, 237, 240) 100%);
  border: 1px solid rgb(217, 214, 196);
  box-shadow: rgba(0, 0, 0, 0.3) 0px 1px 3px 0px;
  color: rgb(31, 31, 31);
  margin: 0px;
  padding: 0px 5px 5px 5px;
  .menu-item {
    margin-top: 5px;
    border-radius: 4px;
    font-size: 14px;
    color: #222222;
    text-align: left;
    padding: 6px 10px;
    cursor: pointer;
    transition: color 0.3s;
  }
  li:hover {
    background-color: #a6a6a6;
    color: #ffffff;
  }
}
</style>
